<template>
  <view class="content">
    <button @tap="startRecording">开始录音</button>
    <button @tap="stopRecording">停止录音</button>
    <view>倒计时: {{ countdown }} 秒</view>
    <view v-if="audioPath">录音文件路径: {{ audioPath }}</view>
    <button v-if="audioPath" @tap="playAudio">播放录音</button>
  </view>
</template>

<script>
export default {
  data() {
    return {
      recorderManager: null,
      countdown: 30,
      timer: null,
      audioPath: '', // 录音文件路径
      audioContext: null // 音频播放上下文
    };
  },
  methods: {
    startRecording() {
      // 初始化录音管理器
      this.recorderManager = uni.getRecorderManager();

      // 监听录音停止事件
      this.recorderManager.onStop((res) => {
        console.log('录音文件路径:', res.tempFilePath);
        this.audioPath = res.tempFilePath; // 保存录音文件路径
      });

      // 开始录音
      this.recorderManager.start({
        duration: 30000, // 录音时长，单位 ms
        sampleRate: 44100,
        numberOfChannels: 1,
        encodeBitRate: 192000,
        format: 'mp3'
      });

      // 开始倒计时
      this.countdown = 30;
      this.timer = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown--;
        } else {
          clearInterval(this.timer);
          this.stopRecording();
        }
      }, 1000);
    },
    stopRecording() {
      if (this.recorderManager) {
        // 停止录音
        this.recorderManager.stop();
        clearInterval(this.timer);
        this.countdown = 0;
      }
    },
    playAudio() {
      if (this.audioPath) {
        // 使用 uni.createInnerAudioContext() 播放录音
        this.audioContext = uni.createInnerAudioContext();
        this.audioContext.src = this.audioPath;
        this.audioContext.play();

        // 监听播放结束事件
        this.audioContext.onEnded(() => {
          console.log('录音播放结束');
        });
      }
    }
  },
  onUnload() {
    // 页面卸载时停止录音
    this.stopRecording();

    // 销毁音频播放上下文
    if (this.audioContext) {
      this.audioContext.destroy();
    }
  }
};
</script>

<style>
.content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
}
</style>
